'use strict';

const db = uniCloud.database();
const collection = db.collection('food-dishes');

exports.main = async (event, context) => {
  const { dishId } = event.data || {};
  
  if (!dishId) {
    return {
      code: 400,
      message: '缺少菜品ID',
      data: null
    };
  }
  
  try {
    // 检查菜品是否存在
    const existingDish = await collection.doc(dishId).get();
    
    if (!existingDish.data || existingDish.data.length === 0) {
      return {
        code: 404,
        message: '菜品不存在',
        data: null
      };
    }
    
    // TODO: 这里可以添加检查菜品是否被订单使用的逻辑
    // 如果菜品有相关订单，应该提示用户先处理相关订单
    
    // 执行删除
    const result = await collection.doc(dishId).remove();
    
    if (result.deleted === 1) {
      return {
        code: 200,
        message: '删除成功',
        data: {
          deletedId: dishId
        }
      };
    } else {
      return {
        code: 500,
        message: '删除失败',
        data: null
      };
    }
  } catch (error) {
    return {
      code: 500,
      message: '删除失败',
      data: null
    };
  }
};